<template>
  <el-card class="classroom-map-card">
    <div class="map-header">
      <h3>教室平面图 - {{ displayDate }}</h3>
      <div class="date-time-picker-group">
        <el-date-picker
          v-model="selectedDateTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :clearable="false"
          @change="fetchClassroomStatus"
        ></el-date-picker>
      </div>
    </div>
    <div class="legend">
      <span class="legend-item available"></span> 可借用
      <span class="legend-item booked"></span> 已借用
      <el-button type="primary" size="small" @click="goTo3DPreview" class="preview-button">
        教室预览
      </el-button>
    </div>
    <div class="floor-plan-layout">
      <div class="room-row top">
        <div
          v-for="room in topRooms"
          :key="room.id"
          :class="['room-box', room.status ? 'booked' : 'available']"
          @click="showClassroomDetails(room)"
        >
          <span class="room-label">{{ room.roomNumber }}</span>
          <span class="door door-bottom-left"></span>
        </div>
      </div>
      <div class="corridor-row">
        <span class="corridor-arrow" v-for="i in arrowCount" :key="i"></span>
      </div>
      <div class="room-row bottom">
        <div
          v-for="room in bottomRooms"
          :key="room.id"
          :class="['room-box', room.status ? 'booked' : 'available']"
          @click="showClassroomDetails(room)"
        >
          <span class="door door-top-left"></span>
          <span class="room-label">{{ room.roomNumber }}</span>
        </div>
      </div>
    </div>

    <div
      v-if="dialogVisible"
      class="custom-dialog-mask"
      @click.self="handleCloseDialog"
    >
      <div class="custom-dialog">
        <div class="custom-dialog-title">教室详情</div>
        <div v-if="selectedClassroom" class="custom-dialog-content">
          <p><strong>教室号:</strong> {{ selectedClassroom.roomNumber }}</p>
          <p><strong>位置:</strong> {{ selectedClassroom.location || '暂无' }}</p>
          <p><strong>容量:</strong> {{ selectedClassroom.capacity }}</p>
          <p><strong>状态:</strong> {{ selectedClassroom.status ? '已借用' : '可用' }}</p>
        </div>
        <div class="custom-dialog-footer">
          <el-button size="small" @click="handleCloseDialog">关闭</el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { getAllClassroomsWithBookingStatus } from '@/services/classroomBookingService';
import { useRouter } from 'vue-router'; // 引入 useRouter

const classrooms = ref([]);
const dialogVisible = ref(false);
const selectedClassroom = ref(null);
const router = useRouter(); // 初始化 router

const now = dayjs();
const defaultStartTime = now.startOf('day').format('YYYY-MM-DDTHH:mm:ss');
const defaultEndTime = now.endOf('day').format('YYYY-MM-DDTHH:mm:ss');
const selectedDateTimeRange = ref([defaultStartTime, defaultEndTime]);

const displayDate = computed(() => {
  if (selectedDateTimeRange.value && selectedDateTimeRange.value.length === 2) {
    const start = dayjs(selectedDateTimeRange.value[0]);
    const end = dayjs(selectedDateTimeRange.value[1]);
    if (start.isSame(end, 'day')) {
      return `${start.format('YYYY年MM月DD日 HH:mm')} - ${end.format('HH:mm')}`;
    } else {
      return `${start.format('YYYY年MM月DD日 HH:mm')} 至 ${end.format('YYYY年MM月DD日 HH:mm')}`;
    }
  }
  return '请选择日期和时间';
});

const fetchClassroomStatus = async () => {
  if (!selectedDateTimeRange.value || selectedDateTimeRange.value.length !== 2) {
    ElMessage.warning('请选择开始和结束日期时间！');
    return;
  }
  const [startTime, endTime] = selectedDateTimeRange.value;
  try {
    const response = await getAllClassroomsWithBookingStatus(startTime, endTime);
    if (response.status === 0) {
      classrooms.value = response.data;
    } else {
      ElMessage.error('获取教室状态失败: ' + response.message);
    }
  } catch (error) {
    console.error('API 调用失败:', error);
    ElMessage.error('获取教室状态失败，请稍后重试。');
  }
};

const showClassroomDetails = (classroom) => {
  selectedClassroom.value = classroom;
  dialogVisible.value = true;
};

const handleCloseDialog = () => {
  dialogVisible.value = false;
  selectedClassroom.value = null;
};

// 新增的跳转方法
const goTo3DPreview = () => {
  router.push({ name: 'TeacherClassroom3D' });
};

// 上下两排房间
const half = computed(() => Math.ceil(classrooms.value.length / 2));
const topRooms = computed(() => classrooms.value.slice(0, half.value));
const bottomRooms = computed(() => classrooms.value.slice(half.value));
// 箭头数量修正：最大排数-1，且最小为0
const arrowCount = computed(() => {
  return Math.max(Math.max(topRooms.value.length, bottomRooms.value.length) - 1, 0);
});

onMounted(() => {
  fetchClassroomStatus();
});
</script>

<style scoped>
.classroom-map-card {
  padding: 20px;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.legend {
  margin-bottom: 20px;
  font-size: 0.9rem;
  color: #666;
  /* 使 legend 内部元素右对齐 */
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 将内容推到右侧 */
  gap: 15px; /* 增加图例项之间的间距 */
}

.legend-item {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 5px;
}

.legend-item.available {
  background-color: #67c23a;
}
.legend-item.booked {
  background-color: #f56c6c;
}

/* 教室预览按钮样式 */
.preview-button {
  margin-left: auto; /* 将按钮推到最右边 */
}

/* 楼层俯视图风格布局 */
.floor-plan-layout {
  width: 100%;
  padding: 40px 0; /* Increased padding for more space */
  background: #f0f4f8; /* Lighter background for a cleaner look */
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(44, 62, 80, 0.1); /* Softer, more pronounced shadow */
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  min-width: 600px;
  border: 1px solid #e0e6ed; /* Subtle border for definition */
}

.room-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 40px; /* Increased gap between rooms */
  margin-bottom: 0;
  position: relative;
  z-index: 2;
}
.room-row.top {
  margin-bottom: 30px; /* More space from corridor */
}
.room-row.bottom {
  margin-top: 30px; /* More space from corridor */
}

.room-box {
  width: 100px; /* Slightly larger rooms */
  height: 60px; /* Slightly taller rooms */
  background: #67c23a;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(44, 62, 80, 0.15); /* Deeper shadow for elevation */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.2rem; /* Slightly larger font */
  color: #fff;
  cursor: pointer;
  position: relative;
  border: 3px solid #fdfdfd; /* Thicker, brighter border */
  transition: transform 0.2s, box-shadow 0.2s, background-color 0.2s;
  overflow: hidden; /* Ensure door stays within bounds if needed */
}
.room-box.booked {
  background: #f56c6c;
}
.room-box.available {
  background: #67c23a;
}
.room-box:hover {
  transform: translateY(-5px) scale(1.05); /* Slight lift and scale */
  box-shadow: 0 12px 30px rgba(44, 62, 80, 0.25); /* More pronounced shadow on hover */
}
.room-label {
  z-index: 2;
  position: relative;
}

/* 门样式 */
.door {
  display: block;
  width: 18px; /* 保持宽度不变，如果需要也可以调整 */
  height: 9px; /* 减小高度 */
  background: #cccccc; /* Grey color for better visibility */
  border: 1px solid #999999; /* Darker border for definition */
  border-radius: 3px; /* Slightly rounded corners */
  position: absolute;
  z-index: 3; /* Ensure door is above room label if they overlap */
}

/* Specific door positions */
.door-bottom-left {
  bottom: 0px; /* 更靠近底部边缘 */
  left: 1px; /* 更靠近左侧边缘 */
}
.door-top-left {
  top: 0px; /* 更靠近顶部边缘 */
  left: 1px; /* 更靠近左侧边缘 */
}

/* 走廊 */
.corridor-row {
  width: 90%; /* Wider corridor */
  height: 60px; /* Taller corridor */
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1;
  background: #e8eff5; /* Light blue corridor color */
  border-radius: 8px;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05); /* Inner shadow for depth */
  border: 1px dashed #c0d0e0; /* Dashed border for a pathway feel */
}
.corridor-row::before {
  content: none; /* Remove the old pseudo-element line */
}
.corridor-arrow {
  width: 70px; /* Longer arrows */
  height: 0;
  border-bottom: 5px solid #f56c6c; /* Thicker arrows */
  margin: 0 10px; /* More space between arrows */
  position: relative;
  z-index: 2;
}
.corridor-arrow::after {
  content: '';
  position: absolute;
  right: -18px; /* Adjust arrow head position */
  top: -6px; /* Adjust arrow head vertical position */
  border: 8px solid transparent;
  border-left: 14px solid #f56c6c; /* Larger arrow head */
}

/* 教室详情对话框内的样式 */
.custom-dialog-mask {
  position: fixed; /* Use fixed for full viewport overlay */
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.3); /* Darker overlay */
  z-index: 1000; /* Higher z-index to ensure it's on top */
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-dialog {
  background: #fff;
  border-radius: 12px; /* Slightly more rounded corners */
  min-width: 350px; /* Slightly wider dialog */
  max-width: 90%;
  box-shadow: 0 10px 40px rgba(0,0,0,0.25); /* More prominent shadow */
  padding: 30px 30px 20px 30px; /* Increased padding */
  position: relative;
  animation: fadeInScale 0.25s ease-out; /* Slightly longer and smoother animation */
}
@keyframes fadeInScale {
  from { opacity: 0; transform: scale(0.95);}
  to { opacity: 1; transform: scale(1);}
}
.custom-dialog-title {
  font-size: 20px; /* Larger title */
  font-weight: bold;
  margin-bottom: 15px; /* More space below title */
  color: #2A4E9A;
  text-align: center;
  border-bottom: 1px solid #eee; /* Separator line */
  padding-bottom: 10px;
}
.custom-dialog-content p {
  margin-bottom: 10px; /* More space between paragraphs */
  color: #333;
  line-height: 1.6; /* Better readability */
}
.custom-dialog-footer {
  text-align: right;
  margin-top: 20px; /* More space above footer buttons */
  padding-top: 10px;
  border-top: 1px solid #eee; /* Separator line */
}
</style>